﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;

namespace RemoterCheckService
{
    public class RemoteCheck
    {
        // 远程端口，大多数为 3389
        const string REMOTE_PORT = "3389";

        public static RemoteState GetRemoteState()
        {
            RemoteState remoteState = new RemoteState();

            IPGlobalProperties iproperties = System.Net.NetworkInformation.IPGlobalProperties.GetIPGlobalProperties();
            TcpConnectionInformation[] ipEndPoints = iproperties.GetActiveTcpConnections();
            foreach (var item in ipEndPoints)
            {
                if (item.LocalEndPoint.ToString() == GetLocalIP() + ":" + REMOTE_PORT)
                {
                    remoteState.IsRemoted = true;
                    remoteState.RemoterIp = item.RemoteEndPoint.Address.ToString();
                }
            }
            return remoteState;
        }

        /// <summary>
        /// 取本机主机ip
        /// </summary>
        /// <returns></returns>
        public static string GetLocalIP()
        {
            try
            {

                string HostName = Dns.GetHostName(); //得到主机名
                IPHostEntry IpEntry = Dns.GetHostEntry(HostName);
                for (int i = 0; i < IpEntry.AddressList.Length; i++)
                {
                    //从IP地址列表中筛选出IPv4类型的IP地址
                    //AddressFamily.InterNetwork表示此IP为IPv4,
                    //AddressFamily.InterNetworkV6表示此地址为IPv6类型
                    if (IpEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork)
                    {
                        string ip = "";
                        ip = IpEntry.AddressList[i].ToString();
                        return IpEntry.AddressList[i].ToString();
                    }
                }
                return "";
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
    }


    public class RemoteState
    {
        public bool IsRemoted;
        public string RemoterIp = "";
    }
}
